import csv
import pandas as pd
import math
import warnings
warnings.filterwarnings('ignore')
def pre(name):
    path = './data/' + name + ".csv"
    data = pd.read_csv(path, encoding='utf-8', engine='python')
    lables=data.columns.tolist() #首行列名

    data=data.values.tolist()   #真实数据
    for i in range(len(data)):
        data[i]=data[i][0].split(',')
    # print(data)
    n=len(data[0])
    for i1 in range(n - 1):
        x1 = []
        y = []
        for row in data:
            x1.append(row[i1])   # 数值
            y.append(row[n - 1]) # 决策属性
        val=[]
        for i in x1:#以不同的值作为划分阈值 计算增益
            x = []
            for j in range(len(x1)):
                if x1[j] >= i:
                    x.append(1)
                else:
                    x.append(-1)

            x_cnt = {}  # 将结果用一个字典存储
            y_cnt = {}  # 将结果用一个字典存储
            # 统计结果
            for value in y:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                y_cnt[value] = y_cnt.get(value, 0) + 1
            y_key = [key for key in y_cnt.keys()]
            y_value = [value for value in y_cnt.values()]
            for value in x:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                x_cnt[value] = x_cnt.get(value, 0) + 1
            x_key = [key for key in x_cnt.keys()]
            x_value = [value for value in x_cnt.values()]
            # print(x_cnt)
            info_x0 = []
            info_x = 0
            for k in range(len(x_key)):
                x0_cnt = {}
                info_x0.append(0)
                # print("计算",lables[i], ":",x_key[k],"的条件熵")
                for l in y_key:
                    for j in range(len(x)):
                        if x[j] == x_key[k] and y[j] == l:
                            x0_cnt[l] = x0_cnt.get(l, 0) + 1
                #print(x0_cnt)
                for v in x0_cnt.values():
                    info_x0[k] = info_x0[k] - v / x_value[k] * math.log(v / x_value[k]) / math.log(2)
                info_x = info_x + x_value[k] / len(x) * info_x0[k]
            val.append(info_x)
        # print(val)
        ind=val.index(min(val)) #找出信息熵最小的，增益最大的
        #print(min(val))
        maxi=x1[ind]
        #print(maxi)
        for d in data:
            if d[i1] >= maxi:
                d[i1] = 1
            else :
                d[i1] = -1

    with open('./data/'+name+".csv", "w", encoding='utf-8', newline='') as csvfile:
        writer = csv.writer(csvfile)
        # 先写入columns_name
        writer.writerow(lables)
        # 写入多行用writerows
        writer.writerows(data)
    print(name,"离散化完成！")
if __name__=='__main__':
    names=['liver','iris','glasss','heart','cleveland']
    #names=['cleveland']
    #names=['heart']
    for name in names:
       #pre.pre(name)
       pre(name)